package org.yocastlong.interceptor;

import org.apache.ibatis.executor.statement.StatementHandler;
import org.apache.ibatis.plugin.Interceptor;
import org.apache.ibatis.plugin.Intercepts;
import org.apache.ibatis.plugin.Invocation;
import org.apache.ibatis.plugin.Signature;
import org.apache.ibatis.reflection.MetaObject;
import org.apache.ibatis.reflection.SystemMetaObject;

import java.sql.Connection;

/**
 * @author 朱海龙
 * 2025/5/30 15:31
 */

@Intercepts(@Signature(type = StatementHandler.class, method = "prepare", args = {Connection.class, Integer.class}))
public class MySqlInterceptor implements Interceptor {

    @Override
    public Object intercept(Invocation invocation) throws Throwable {
        StatementHandler target = (StatementHandler) invocation.getTarget();

        MetaObject metaObject = SystemMetaObject.forObject(target);

        if (metaObject.hasGetter("h")) {
            target = (StatementHandler) metaObject.getValue("h");
            metaObject = SystemMetaObject.forObject(target);
        }


        String sql = metaObject.getValue("delegate.boundSql.sql")
                               .toString();
        if (sql.toLowerCase().contains("select")) {
            sql = sql.concat(" and 1=1 ");
            metaObject.setValue("delegate.boundSql.sql", sql);
        }
        return invocation.proceed();
    }
}
